<template>
  <div class="search-suggestion">
    <van-cell
      icon="search"
      v-for="(text, index) in suggestList"
      :key="index"
      @click="$emit('search', text)"
    >
      <div slot="title" v-html="hightligth(text)"></div
    ></van-cell>
  </div>
</template>

<script>
import { getSearchSuggestion } from '../../../api/search'
import { debounce } from 'lodash'
export default {
  name: 'Searchsuggestion',

  data() {
    return {
      suggestList: []
    };
  },
  props: {
    searchText: {
      type: String,
      require: true
    }
  },
  watch: {
    searchText: {
      // handler(value) {
      //   console.log(value);
      //   this.loadSearchSuggestion(value)
      // },
      handler: debounce(function (value) {
        this.loadSearchSuggestion(value)
      }, 200),
      immediate: true
    }
  },
  mounted() {
  },

  methods: {
    async loadSearchSuggestion(q) {
      try {
        const { data } = await getSearchSuggestion(q)
        console.log(data)
        this.suggestList = data.data.options
      } catch (error) {
        this.$toast('获取文章建议失败!,请稍后重试')
      }
    },
    hightligth(text) {
      const hightligthStr = `<span style="color: red">${this.searchText}</span>`
      //正则表达式//中间的内容都会当作匹配字符来使用，而不是数据变量
      //如果需要根据数据变量动态的创建正则表达式，则手动new RegExp
      // RegExp正则表达式构造函数
      //参数1:匹配模式字符串，它会根据这个字符串创建正则对象
      //参数2:匹配模式，要写到字符串中
      //gi表示正则字符串全部匹配和不区分大小写
      const reg = new RegExp(this.searchText, 'gi')
      return text.replace(reg, hightligthStr)
    }
  }
};
</script>

<style lang="less" scoped>
</style>